package cn.yuznu.www;

import javax.swing.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ChatClient extends Frame {

    private TextArea ta = new TextArea(); //   显示聊天记录
    private TextField tf = new TextField(20); //  输入文本
    private Socket s = null;
    private DataOutputStream dos = null;
    private DataInputStream dis = null;
    private String username;

    public void launchFrame() throws Exception { //设置UI
        this.setLayout(new BorderLayout());
        this.add(ta, BorderLayout.CENTER);

        JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        southPanel.add(tf);
        JButton sendButton = new JButton("发送"); // 创建发送按钮
        sendButton.addActionListener(new ActionListener() { //    发送按钮的监听器
            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    String sSend = tf.getText();
                    if (sSend.trim().length() == 0) return;
                    send(sSend);                //发送消息
                    tf.setText("");
                    ta.append(username + ": " + sSend + "\n"); //显示发送的聊天记录
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        southPanel.add(sendButton);

        tf.addKeyListener(new KeyAdapter() { //回车监听器
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    try {
                        String sSend = tf.getText();
                        if (sSend.trim().length() == 0) return;
                        send(sSend); // 调用send方法发送消息
                        tf.setText("");
                        ta.append(username + ": " + sSend + "\n");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        this.add(southPanel, BorderLayout.SOUTH); // 将底部面板添加到窗口底部

        this.addWindowListener(new WindowAdapter() { // 为窗口添加关闭事件监听器
            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    disconnect(); // 断开连接
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                System.exit(0); // 退出程序
            }
        });
        setBounds(300, 300, 300, 400);
        setVisible(true);
        tf.requestFocus(); //光标
    }

    public ChatClient() throws Exception { // 构造方法
        s = new Socket("127.0.0.1", 8080);
        launchFrame();
        showLoginDialog();
        (new Thread(new ReceiveThread())).start(); // 启动接收消息的线程
    }

    private void showLoginDialog() { // 显示登录对话框的方法
        String[] options = {"登录", "注册"};
        int n = JOptionPane.showOptionDialog(null, "您想要登录还是注册？", "聊天客户端",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (n == 0) {
            login();
        } else if (n == 1) {
            register();
        }
    }

    private void login() {                     // 登录方法
        String username = JOptionPane.showInputDialog("请输入您的用户名:");
        String password = JOptionPane.showInputDialog("请输入您的密码:");
        try {
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
            dos.writeUTF("LOGIN"); // 发送登录命令到服务器
            dos.writeUTF(username); // 发送用户名到服务器
            dos.writeUTF(password);
            String response = dis.readUTF(); // 接收服务器响应
            if ("LOGIN_SUCCESS".equals(response)) {
                this.username = username; // 设置当前用户名
                JOptionPane.showMessageDialog(null, "登录成功。");
            } else {
                JOptionPane.showMessageDialog(null, "登录失败。请重试或注册。");
                showLoginDialog(); // 重新显示登录对话框
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "无法连接到服务器: " + e.getMessage());
            System.exit(1);
        }
    }

    private void register() { // 注册
        String username = JOptionPane.showInputDialog("请输入新用户名:");
        String password = JOptionPane.showInputDialog("请输入新密码:");
        try {
            dos = new DataOutputStream(s.getOutputStream());
            dos.writeUTF("REGISTER"); // 发送注册命令到服务器
            dos.writeUTF(username); // 发送用户名到服务器
            dos.writeUTF(password);
            String response = dis.readUTF(); // 接收服务器响应
            if ("REGISTER_SUCCESS".equals(response)) {
                JOptionPane.showMessageDialog(null, "注册成功。请登录。");
                showLoginDialog();
            } else {
                JOptionPane.showMessageDialog(null, "注册失败。");
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "无法连接到服务器: " + e.getMessage());
            System.exit(1);
        }
    }

    public void send(String str) throws Exception {  //发送
        dos.writeUTF(str);
    }

    public void disconnect() throws Exception {//断开
        s.close();
    }

    class ReceiveThread implements Runnable { // 接收消息的线程类
        @Override
        public void run() {
            if (s == null) return;
            try {
                String str = dis.readUTF(); // 接收服务器发送的消息
                while (str != null) {
                    ta.append(str + "\n"); // 在文本区域显示接收到的消息
                    str = dis.readUTF(); // 继续接收下一条消息
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new ChatClient();
    }
}